import React, { useEffect, useState } from 'react';
import { Card, List, Space, Tag, Button, Input, Empty, Spin, Tooltip, Popconfirm, Badge } from 'antd';
import { SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined, BookOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import { fetchKnowledgeBases } from '../../store/slices/knowledgeBase';
import { RootState } from '../../store';
import PageHeader from '../common/PageHeader';
import { KnowledgeBase } from '../../types/knowledgeBase';

const { Search } = Input;

const KnowledgeBaseList: React.FC = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const { knowledgeBases, loading } = useSelector((state: RootState) => state.knowledgeBase);

  const [searchTerm, setSearchTerm] = useState('');
  const [filteredKnowledgeBases, setFilteredKnowledgeBases] = useState<KnowledgeBase[]>([]);

  useEffect(() => {
    dispatch(fetchKnowledgeBases() as any);
  }, [dispatch]);

  useEffect(() => {
    if (searchTerm) {
      setFilteredKnowledgeBases(
        knowledgeBases.filter(
          kb => kb.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                kb.description.toLowerCase().includes(searchTerm.toLowerCase())
        )
      );
    } else {
      setFilteredKnowledgeBases(knowledgeBases);
    }
  }, [searchTerm, knowledgeBases]);

  const handleSearch = (value: string) => {
    setSearchTerm(value);
  };

  const handleCreateKnowledgeBase = () => {
    navigate('/knowledge-base/create');
  };

  const handleEdit = (id: number) => {
    navigate(`/knowledge-base/edit/${id}`);
  };

  const handleView = (id: number) => {
    navigate(`/knowledge-base/${id}`);
  };

  const handleDelete = (id: number) => {
    // 这里添加删除知识库的逻辑
    console.log('删除知识库:', id);
  };

  const extraContent = (
    <Space>
      <Search 
        placeholder="搜索知识库" 
        onSearch={handleSearch} 
        style={{ width: 300 }} 
        allowClear
      />
      <Button type="primary" icon={<PlusOutlined />} onClick={handleCreateKnowledgeBase}>
        创建知识库
      </Button>
    </Space>
  );

  return (
    <div className="knowledge-base-list">
      <PageHeader 
        title="知识库列表" 
        extra={extraContent}
        breadcrumbs={[
          { title: '首页', path: '/' },
          { title: '知识库列表' },
        ]}
      />

      <Spin spinning={loading}>
        {filteredKnowledgeBases.length > 0 ? (
          <List
            grid={{
              gutter: 16,
              xs: 1,
              sm: 1,
              md: 2,
              lg: 3,
              xl: 3,
              xxl: 4,
            }}
            dataSource={filteredKnowledgeBases}
            renderItem={(item) => (
              <List.Item>
                <Card
                  hoverable
                  title={
                    <Space>
                      <BookOutlined style={{ color: '#1890ff' }} />
                      {item.name}
                      {item.isPrivate && (
                        <Badge status="processing" text={<Tag color="blue">私有</Tag>} />
                      )}
                    </Space>
                  }
                  extra={
                    <Space>
                      <Tooltip title="查看详情">
                        <Button 
                          type="text" 
                          shape="circle" 
                          icon={<EyeOutlined />} 
                          onClick={() => handleView(item.id)} 
                        />
                      </Tooltip>
                      <Tooltip title="编辑">
                        <Button 
                          type="text" 
                          shape="circle" 
                          icon={<EditOutlined />} 
                          onClick={() => handleEdit(item.id)} 
                        />
                      </Tooltip>
                      <Tooltip title="删除">
                        <Popconfirm
                          title="确定要删除此知识库吗?"
                          onConfirm={() => handleDelete(item.id)}
                          okText="确定"
                          cancelText="取消"
                        >
                          <Button 
                            type="text" 
                            shape="circle" 
                            danger 
                            icon={<DeleteOutlined />} 
                          />
                        </Popconfirm>
                      </Tooltip>
                    </Space>
                  }
                >
                  <div style={{ height: 80, overflow: 'hidden', textOverflow: 'ellipsis' }}>
                    {item.description || '暂无描述'}
                  </div>
                  <div style={{ marginTop: 16, display: 'flex', justifyContent: 'space-between', color: 'rgba(0, 0, 0, 0.45)' }}>
                    <span>文档数量: {item.documentCount}</span>
                    <span>创建时间: {new Date(item.createdAt).toLocaleDateString()}</span>
                  </div>
                  {item.tags && item.tags.length > 0 && (
                    <div style={{ marginTop: 16 }}>
                      {item.tags.map(tag => (
                        <Tag key={tag} color="default">{tag}</Tag>
                      ))}
                    </div>
                  )}
                </Card>
              </List.Item>
            )}
          />
        ) : (
          <Empty 
            description={searchTerm ? "没有找到匹配的知识库" : "暂无知识库，请创建一个新的知识库"}
            image={Empty.PRESENTED_IMAGE_SIMPLE} 
          />
        )}
      </Spin>
    </div>
  );
};

export default KnowledgeBaseList; 